<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 手机短信接口
 */
class Myshopline extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
//        $this->model = new \app\admin\model\Feditionordershopline;
    }

    /**
     * 后台自动获取数据
     * $type 1 拉取所有订单
     * $type 2 实时拉取当下订单
     * $type 3 拉取之前的订单
     */
    public function accounturl_iscustom()
    {
        $type = $this->request->request('type');
        if(!empty($type)){
            $iscustom = Db::name('fedition_accounturl')
                ->where('isshopline',1)
                ->where('status','normal')
                ->select();
            if($iscustom){
                foreach ($iscustom as $k => $v) {
                    $this->orders($v,$type);
                }
            }
        }
        $this->success('操作成功');
    }
    /**
     * orders
     */
    public function orders($iscustom,$type)
    {
//      $financial_status
//            temp 暂存，新站不支持该状态
//            pending 处理中
//            removed 已刪除，新站不支持该状态
//            confirmed 已确认，新站不支持该状态
//            completed 已完成，新站不支持该状态
//            cancelled 已取消
//      $orderDeliveryStatus
//          订单发货状态，新增
//          处理中-100,
//          已确认-150,
//          已发货-400
        $url = "https://open.shoplineapp.com/v1/orders";
        if($type == 3){
            $before_ordershopify = Db::name('fedition_ordershopify')
                ->where('accounturl',$iscustom['id'])
                ->order('ycreated_at asc')
                ->find();
            if($before_ordershopify){
                $created_at_max = $before_ordershopify['ycreated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1.'T'.$created_at_max2.'-04:00';
            }
            //拉取之前的订单
            $url = $url.'?created_at_max='.$created_at_max;
        }
        if($type == 2){
            $last_ordershopify = Db::name('fedition_ordershopify')
                ->where('accounturl',$iscustom['id'])
                ->order('yupdated_at desc')
                ->find();
            if($last_ordershopify){
                $updated_at_min = $last_ordershopify['yupdated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url.'?updated_at_min='.$updated_at_min;
        }
        if($type == 1){
            $per_page = 50;
            $page = 1;
            $sort_by = 'desc';
            $url = $url.'?sort_by='.$sort_by.'&per_page='.$per_page.'&page='.$page;
        }
//        dump($url);die;
        $data = $this->geturl($url,$iscustom['shoplinetoken']);
        if($data){
            $data = json_decode($data,true);
//            dump($orders);die;
            $orders = $data['items'];
            if(is_array($orders) && !empty($orders)){
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as $k => $v) {
                    $arr['id'] = $v['id'];
                    $arr['order_number'] = $v['order_number'];
                    //美国时间转北京时间
                    $arr['ycreated_at'] = $v['created_at'];
                    $arr['yupdated_at'] = $v['updated_at'];
                    //显示美国时间,中国比美国快十二个小时
                    $arr['created_at'] = strtotime($v['created_at']) - 12*3600;
                    $arr['updated_at'] = strtotime($v['updated_at']) - 12*3600;
                    $arr['fulfillment_status'] = $v['orderDeliveryStatus'];



                    if(isset($v['order_payment']['total']['label'])){
                         $arr['financial_status'] = $v['status'];
                    }
                    $arr['subtotal_price'] = $v['subtotal_price'];
                    $arr['total_price'] = $v['total_price'];
                    $arr['currency'] = $v['currency'];
                    if (!empty($v['financial_status'])) {
                        $arr['financial_status'] = $v['financial_status'];
                    } else {
                        $arr['financial_status'] = 'unfulfilled';
                    }
                    $arr['accounturl'] = $iscustom['id'];
                    $arr['gateway'] = $v['gateway'];

                    if(isset($v['fulfillments'][0]['tracking_company'])){
                        $arr['tracking_company'] = $v['fulfillments'][0]['tracking_company'];
                    }
                    if(isset($v['fulfillments'][0]['tracking_number'])){
                        $arr['tracking_number'] = $v['fulfillments'][0]['tracking_number'];
                    }
                    $row = $this->model->get($v['id']);
                    if($row){
                        if($row['yupdated_at'] !== $arr['yupdated_at']){
                            $row->save($arr);
                            //订单有更新 发货或者退款
                            $this->addlogshopify(1,$arr,3);
                            $this->savesales($arr['created_at']);//传时间戳
                        }
                    }else{
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $this->model->insert($arr);
                    }
                }
            }
            $this->addlogshopify(1,$iscustom,1);
        }else{
            $this->addlogshopify(0,$iscustom,1);
        }
        return true;
    }

    function geturl($url,$token){
        $headerArray = array("Accept:application/json","Content-Type:application/json;",'Authorization:Bearer '.$token);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl($url,$data = array(),$iscustom=null){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['shopifyapikey'];
        $secretapikey = $iscustom['shopifysecretapikey'];

        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
